package com.kmzx.one.project.config.listener;

import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.ChannelActivity;
import com.kmzx.one.project.entity.ChannelBuying;
import com.kmzx.one.project.entity.ChannelProduct;
import com.kmzx.one.project.entity.UserOrder;
import com.kmzx.one.project.entity.WxUser;
import com.kmzx.one.project.events.ExpandUserEvent;
import com.kmzx.one.project.mapper.ExpandUserMapper;
import com.kmzx.one.project.mapper.UserOrderMapper;
import com.kmzx.one.project.mapper.WxUserMapper;
import com.kmzx.one.project.others.dso.UserOrderDso;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Project one
 * @Author: carol
 * @Date: 2020/5/29-14:23
 */
@Component(value = "expandUserEventListener")
public class ExpandUserEventListener {

    private static Logger logger = LoggerFactory.getLogger(JRedisMessageListener.class);


    @Autowired
    UserOrderMapper userOrderMapper;

    @Autowired
    WxUserMapper wxUserMapper;

    @Autowired
    ExpandUserMapper expandUserMapper;

    @Async
    @EventListener(classes = {ExpandUserEvent.class})
    public void defaultPartnerViewEvent(ExpandUserEvent expandUserEvent) throws Exception {
        logger.info("用户支付完成后校验是不是,推广用户");
        String orderId = expandUserEvent.getOrderId();
        // 主订单
        UserOrder userOrder = userOrderMapper.selectById(orderId);

        // 用户id
        String userId = userOrder.getUserId();

        // 用户信息
        WxUser wxUser = wxUserMapper.selectById(userId);


        Integer identityType = wxUser.getIdentityType();

        if (identityType != null) {
            if (identityType != 0) {
                ChannelActivity channelActivity = expandUserMapper.selectChannelActivityById(String.valueOf(identityType));
                if (channelActivity != null) {
                    Integer buyBrowsingNum = channelActivity.getBuyBrowsingNum();
                    Integer buyOtherNum = channelActivity.getBuyOtherNum();

                    List<ChannelProduct> channelProducts = expandUserMapper.selectChannelProduct(channelActivity.getId());
                    List<UserOrderDso> userOrderDsos = userOrderMapper.selectUserOrderSubDetail(orderId);
                    int beProdNum = 0;
                    ArrayList<ChannelBuying> buyings = new ArrayList<>();
                    for (ChannelProduct channelProduct : channelProducts) {
                        String productId = channelProduct.getProductId();
                        String cSkuId = channelProduct.getSkuId();
                        for (UserOrderDso orderDso : userOrderDsos) {
                            String skuId = orderDso.getSkuId();
                            long prodNum = orderDso.getProdNum();
                            if (skuId.equals(cSkuId)) {
                                beProdNum += prodNum;
                            }
                                ChannelBuying buying = new ChannelBuying();
                                LocalDateTime now = LocalDateTime.now();
                                LocalDateTime realPayTime = now.plusSeconds(-20);

                                ZoneId zone = ZoneId.systemDefault();
                                Instant instant = realPayTime.atZone(zone).toInstant();
                                Date date = Date.from(instant);


                                buying.setId(UUIDGenerator.generate())
                                        .setBuyingTime(date).setBuyNum(prodNum)
                                        .setChannelId(channelActivity.getId())
                                        .setProductId(productId)
                                        .setSkuId(skuId)
                                        .setUserId(userOrder.getUserId());
                                buying.setPayMoney(orderDso.getEndMoney());

                                buyings.add(buying);
                        }
                    }

                    if (beProdNum != 0) {
                        buyBrowsingNum += beProdNum;
                        channelActivity.setBuyBrowsingNum(buyBrowsingNum);
                        channelActivity.setBuyOtherNum(userOrder.getProdNum() - beProdNum);

                        logger.info("更新渠道推广数据,前,...,购买链接商品数:{},购买其他商品数:{}", buyBrowsingNum, buyOtherNum);
                        expandUserMapper.updateChannelActivity(channelActivity.getBuyBrowsingNum(), channelActivity.getBuyOtherNum(), channelActivity.getId());
                        logger.info("更新渠道推广数据,后...,购买链接商品数:{},购买其他商品数:{}", channelActivity.getBuyBrowsingNum(), channelActivity.getBuyOtherNum());

                        expandUserMapper.batchInsertChannelBuying(buyings);

                        logger.info("批量新增订单购买数据:{}", buyings);
                    } else {
                        channelActivity.setBuyBrowsingNum(buyBrowsingNum);
                        channelActivity.setBuyOtherNum(buyOtherNum + userOrder.getProdNum());

                        logger.info("更新渠道推广数据,前,...,购买链接商品数:{},购买其他商品数:{}", buyBrowsingNum, buyOtherNum);
                        expandUserMapper.updateChannelActivity(channelActivity.getBuyBrowsingNum(), channelActivity.getBuyOtherNum(), channelActivity.getId());
                        logger.info("更新渠道推广数据,后...,购买链接商品数:{},购买其他商品数:{}", channelActivity.getBuyBrowsingNum(), channelActivity.getBuyOtherNum());
                    }


                    logger.info("用户支付完成后校验是推广用户,订单id是:{}", orderId);
                }
            } else {
                logger.info("用户支付完成后校验是不是,推广用户,暂无发现,订单id是:{}", orderId);
            }
        } else {
            logger.info("用户支付完成后校验是不是,推广用户,暂无发现,订单id是:{}", orderId);
        }
    }
}
